package com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.aibkMarkZht

import android.content.Context
import android.os.Handler
import android.util.Log
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkDialog.ShowDialogTools
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.LancooMethod
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseFragment
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.EvalBody
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.QuesMarkDeatil
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.StuAnswerMark
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.SubjectData
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.AibkQuesMarkActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.MarkFragmentParentView
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.adapter.MyVpFragmentPagerAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.adapter.SubjectAdapter
import com.lancoo.znbkxx.teacher.help.KeyboardStateObserverHelp
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.WebStyleUtils
import com.lancoo.znbkxx.teacher.utils.WebStyleUtils.returnImageUrlsFromHtml
import com.lancoo.znbkxx.teacher.widget.KWebView
import kotlinx.android.synthetic.main.aibk_fragment_mark_model_splitlayout.view.*
import kotlinx.android.synthetic.main.aibk_include_article_view.view.*
import kotlinx.android.synthetic.main.aibk_include_loading_refresh.view.*
import kotlinx.android.synthetic.main.aibk_include_mark_view.*
import kotlinx.android.synthetic.main.aibk_include_mark_view.view.*
import kotlinx.android.synthetic.main.aibk_include_parent_audioplayer_a.view.*
import kotlinx.android.synthetic.main.aibk_include_ques_web_ask_view.*
import kotlinx.android.synthetic.main.aibk_include_ques_web_ask_view.view.*
import kotlinx.android.synthetic.main.aibk_include_question_information_view.view.*
import java.util.*

class MarkFragmentZht(
        val indexA: Int,
        val indexB: Int,
        val activity: AibkQuesMarkActivity,
        var quesId: String,
        var startIndex: String
) : KBaseFragment() {
    private var rootView: View? = null
    private lateinit var quesMarkDeatil: QuesMarkDeatil
    private var isAddView = false
    private var fragmentList: MutableList<Fragment>? = ArrayList()
    private var itemList: ArrayList<SubjectData> = ArrayList()
    private lateinit var subjectAdapter: SubjectAdapter
    private var lastPosition = 0
    private var typeNo = "K"

    override fun createLayout(): Int {
        return R.layout.aibk_fragment_mark_model_splitlayout
    }

    override fun initView(view: View?) {
        rootView = view
        rootView!!.RlGifLoading.visibility = View.VISIBLE
        rootView!!.RlAudioPlayer.visibility = View.GONE
        rootView!!.RlArticleView.visibility = View.GONE
        adjustPan()
    }

    //调整布局高度
    private fun adjustPan() {
        val screenHeight = DensityUtils.getScreenHeight(getActivity())
        rootView!!.sp_layout.setmSplitHeight(screenHeight * 2 / 5)
        KeyboardStateObserverHelp.getKeyboardStateObserver(getActivity()).setKeyboardVisibilityListener(object : KeyboardStateObserverHelp.OnKeyboardVisibilityListener {
            override fun onKeyboardShow() {
                rootView!!.sp_layout.setmSplitHeight(300)
            }

            override fun onKeyboardHide() {
                rootView!!.sp_layout.requestFocus()
                rootView!!.sp_layout.setmSplitHeight(screenHeight * 2 / 5)
            }
        })
    }


    private fun initSubjectAdapter() {
        setSubjectData()
        itemList[0].isSelect = true
        subjectAdapter = SubjectAdapter(activity, itemList)
        subjectAdapter.setOnItemClickListener(object : SubjectAdapter.OnItemClickListener {
            override fun onItemClickPlay(position: Int, view: View?) {
                VpAnswer.setCurrentItem(position, true)
            }
        })
        rv_subject.layoutManager = GridLayoutManager(context, 5)
        rv_subject.adapter = subjectAdapter
    }

    private fun setSubjectData() {
        itemList.clear()
        for (i in quesMarkDeatil!!.QuesDetail.ChildList.indices) {
            if (quesMarkDeatil!!.QuesDetail.ChildList[i].SortIndexType == 0) {
                var item = SubjectData()
                item.childIndex = quesMarkDeatil!!.QuesDetail.ChildList[i].ItemList[0].SortIndex
                item.realChildIndex = "0"
                item.realIndex = i.toString()
                itemList.add(item)
            } else {
                for (j in quesMarkDeatil!!.QuesDetail.ChildList[i].ItemList.indices) {
                    var item = SubjectData()
                    item.childIndex = quesMarkDeatil!!.QuesDetail.ChildList[i].ItemList[j].SortIndex
                    item.realChildIndex = j.toString()
                    item.realIndex = i.toString()
                    itemList.add(item)
                }
            }
        }
    }

    /*
    * 显示试题内容
    * */
    private fun showQuestionView() {

        //是否显示来源
        var resource = quesMarkDeatil.QuesDetail.Resource
        if (resource.isEmpty()) {
            rootView!!.IncludeQuesInformationView.visibility = View.GONE
        } else {
            rootView!!.IncludeQuesInformationView.visibility = View.VISIBLE
            rootView!!.IncludeQuesInformationView.TvSourceFrom.text = "来源: $resource"
            //隐藏试题准确率
            rootView!!.IncludeQuesInformationView.TvScoreRate.visibility = View.GONE
        }

        //加载题干内容
        var ask = quesMarkDeatil.QuesDetail.QuesBody
        var itemAnswerAll = ""
        var itemAnalysisAll = ""
        var childListSize = quesMarkDeatil.QuesDetail.ChildList.size
        for (a in 0 until childListSize) {
            val childAnswerType = quesMarkDeatil.QuesDetail.ChildList[a].ChildAnswerType
            if (childAnswerType == 32) {//匹配题
                val childAsk = quesMarkDeatil.QuesDetail.ChildList[a].ChildAsk

                //组装题干
                var optionPartAll = ""
                val childOptionListSize = quesMarkDeatil.QuesDetail.ChildList[a].ChildOptionList.size
                for (i in 0 until childOptionListSize) {
                    val optionIndex = quesMarkDeatil.QuesDetail.ChildList[a].ChildOptionList[i].OptionIndex
                    val option = quesMarkDeatil.QuesDetail.ChildList[a].ChildOptionList[i].Option
                    val optionPart = "$optionIndex. $option"
                    if (optionPartAll.isEmpty()) {
                        optionPartAll = optionPart
                    } else {
                        optionPartAll = "$optionPartAll<br>$optionPart"
                    }
                }
                ask = "$childAsk<br>$optionPartAll"

                //组装参考答案
                var itemAnswerPartAll = ""
                val itemListsize = quesMarkDeatil.QuesDetail.ChildList[a].ItemList.size
                for (i in 0 until itemListsize) {
                    val itemSortIndex = quesMarkDeatil.QuesDetail.ChildList[a].ItemList[i].ItemSortIndex
                    val itemAnswer = quesMarkDeatil.QuesDetail.ChildList[a].ItemList[i].ItemAnswer
                    if (itemAnswerPartAll.isEmpty()) {
                        itemAnswerPartAll = "$itemSortIndex. $itemAnswer"
                    } else {
                        itemAnswerPartAll = "$itemAnswerPartAll<br>$itemSortIndex. $itemAnswer"
                    }
                }
                if (itemAnswerAll.isEmpty()) {
                    itemAnswerAll = itemAnswerPartAll
                } else {
                    itemAnswerAll = "$itemAnswerAll<br>$itemAnswerPartAll"
                }

            } else if (childAnswerType == 2 || childAnswerType == 4) {//简答
                val childAsk = quesMarkDeatil.QuesDetail.ChildList[a].ChildAsk
                val itemSortIndex = quesMarkDeatil.QuesDetail.ChildList[a].ItemList[0].ItemSortIndex
                val childAnswer = quesMarkDeatil.QuesDetail.ChildList[a].ChildAnswer
                val childAnalysis = quesMarkDeatil.QuesDetail.ChildList[a].ChildAnalysis

                //组装题干
                ask = "$ask<br><br>$itemSortIndex. $childAsk"

                //组装参考答案
                if (itemAnswerAll.isEmpty()) {
                    itemAnswerAll = itemSortIndex + ". " + LancooMethod.getNewItemAnswer(childAnswer, false)
                } else {
                    itemAnswerAll = itemAnswerAll + "<br>" + itemSortIndex + ". " + LancooMethod.getNewItemAnswer(childAnswer, false)
                }
            } else if (childAnswerType == 1) {//选择
                val childAsk = quesMarkDeatil.QuesDetail.ChildList[a].ChildAsk
                val itemSortIndex = quesMarkDeatil.QuesDetail.ChildList[a].ItemList[0].ItemSortIndex
                val itemAnswer = quesMarkDeatil.QuesDetail.ChildList[a].ItemList[0].ItemAnswer
                val itemAnalysis = quesMarkDeatil.QuesDetail.ChildList[a].ItemList[0].ItemAnalysis

                //组装题干
                var optionPartAll = ""
                val childOptionListSize = quesMarkDeatil.QuesDetail.ChildList[a].ChildOptionList.size
                for (i in 0 until childOptionListSize) {
                    val optionIndex = quesMarkDeatil.QuesDetail.ChildList[a].ChildOptionList[i].OptionIndex
                    val option = quesMarkDeatil.QuesDetail.ChildList[a].ChildOptionList[i].Option
                    val optionPart = "$optionIndex. $option"
                    if (optionPartAll.isEmpty()) {
                        optionPartAll = optionPart
                    } else {
                        optionPartAll = "$optionPartAll<br>$optionPart"
                    }
                }
                ask = "$ask<br><br>$itemSortIndex. $childAsk<br>$optionPartAll"

                //组装参考答案
                if (itemAnswerAll.isEmpty()) {
                    itemAnswerAll = itemSortIndex + ". " + LancooMethod.getNewItemAnswer(itemAnswer, false)
                } else {
                    itemAnswerAll = itemAnswerAll + "<br>" + itemSortIndex + ". " + LancooMethod.getNewItemAnswer(itemAnswer, false)
                }

            }
        }

        var isEmptyAnalysis = true
        outLoop@ for (a in 0 until childListSize) {
            val childAnalysis = quesMarkDeatil.QuesDetail.ChildList[a].ChildAnalysis
            if (childAnalysis.isNotEmpty()) {
                isEmptyAnalysis = false
                break@outLoop
            }
            val itemListSize = quesMarkDeatil.QuesDetail.ChildList[a].ItemList.size
            for (b in 0 until itemListSize) {
                val itemSortIndex = quesMarkDeatil.QuesDetail.ChildList[a].ItemList[b].ItemSortIndex
                val itemAnalysis = quesMarkDeatil.QuesDetail.ChildList[a].ItemList[b].ItemAnalysis
                if (itemAnalysisAll.isEmpty()) {
                    itemAnalysisAll = "$itemSortIndex. $itemAnalysis"
                } else {
                    itemAnalysisAll = "$itemAnalysisAll<br>$itemSortIndex. $itemAnalysis"
                }
            }
        }
        if (isEmptyAnalysis) {
            itemAnalysisAll = activity.getString(R.string.aibk_no_analyze) //...略
        }

        itemAnswerAll = "<div style=\"color:#00b30d;\">【参考答案】</div>\n$itemAnswerAll"
        itemAnalysisAll = "<div style=\"color:#00afff;\">【答案解析】</div>\n$itemAnalysisAll"
        ask = "$ask<br><br>$itemAnswerAll<br><br>$itemAnalysisAll"
        ask = ask.replace("clickFunction", "Android.clickFunction")

        if (WebStyleUtils.hasTable(ask)) {
            WebStyleUtils.showWebViewCssStyle(activity, WvAsk, ask, false)
        } else {
            WebStyleUtils.showWebViewCssStyle(activity, WvAsk, ask, true)
        }
        WvAsk.addJavascriptInterface(
                JSInterface(
                        activity,
                        returnImageUrlsFromHtml(ask)
                ), "Android"
        )
        WvAsk.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                rootView!!.RlWebLoading.visibility = View.GONE
                WebStyleUtils.setWebImageClick(view, "Android")
                showBlankView()
            }
        }

        WvAsk.setOnScrollChangeListener(object : KWebView.OnScrollChangeListener {
            override fun onPageEnd(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "已经到达地端")
            }

            override fun onPageTop(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "已经到达顶端")
            }

            override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {

            }
        })

        //加载作答区域
        resetStuAnswer()
        val mAdapter = MyVpFragmentPagerAdapter(childFragmentManager, fragmentList as ArrayList<Fragment>)
        rootView!!.VpAnswer.adapter = mAdapter
        rootView!!.VpAnswer.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                itemList[lastPosition].isSelect = false
                itemList[lastPosition].isShowMark = false
                itemList[position].isSelect = true
                //当前显示
                setStuAnswer(lastPosition)
                //用于保存评阅
                deEvalJob(lastPosition)
                resetStuAnswer()
                subjectAdapter.notifyDataSetChanged()
                VpAnswer.adapter?.notifyDataSetChanged()
                lastPosition = position
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
    }

    private fun resetStuAnswer() {
        fragmentList!!.clear()
        for (i in quesMarkDeatil.QuesDetail.ChildList.indices) {
            if (quesMarkDeatil.QuesDetail.ChildList[i].SortIndexType == 0) {
                (fragmentList as ArrayList<Fragment>)
                        .add(MarkFragmentParentView(activity, null, quesMarkDeatil.StuAnswerList!!, i, i, typeNo))
                setShowMark(quesMarkDeatil.StuAnswerList!!)
            } else {
                for (j in quesMarkDeatil.QuesDetail.ChildList[i].ItemList.indices) {
                    (fragmentList as ArrayList<Fragment>)
                            .add(MarkFragmentParentView(activity, null, quesMarkDeatil.StuAnswerList!!, i, j, typeNo))
                    setShowMark(quesMarkDeatil.StuAnswerList!!)
                }
            }
        }

    }


    //JS点击事件处理
    inner class JSInterface(var context: Context, var imageUrls: Array<String>?) {

        @JavascriptInterface
        fun clickFunction(position: String) {
            return
        }

        //java回调js代码，不要忘了@JavascriptInterface这个注解，不然点击事件不起作用
        @JavascriptInterface
        fun openImage(img: String, pos: Int) {
            val paths = ArrayList<String>()
            paths.add(img)
            Log.e("openImage", "$pos========点击了图片=========$img")
            ShowDialogTools.showBigImageDialog(activity, img)
        }
    }

    private fun showBlankView() {

        val itemListSize = quesMarkDeatil!!.QuesDetail.ChildList[0].ItemList.size
        for (b in 0 until itemListSize) {
            val itemSortIndex = quesMarkDeatil!!.QuesDetail.ChildList[0].ItemList[b].ItemSortIndex

            WvAsk.loadUrl("javascript:setBackGroundColor('" + "blank" + itemSortIndex +
                    "','" + "#00000000" + "','" + "0px" + "','" + "1px solid #848484" + "')")
            showBlankItemAnswer(itemSortIndex)
        }
    }

    private fun showBlankItemAnswer(
            itemSortIndex: String
    ) {
        WvAsk.loadUrl(
                "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                        + "','" + "&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp" + " ')"
        )

    }

    override fun setMenuVisibility(menuVisible: Boolean) {
        super.setMenuVisibility(menuVisible)
        if (menuVisible) {
            if (!isAddView) {
                Handler().postDelayed({
                    val parentActivity: AibkQuesMarkActivity? =
                            getActivity() as AibkQuesMarkActivity?
                    parentActivity?.getSingQuesMarkDetail(quesId, startIndex)
                    parentActivity?.setDetailListener(object : AibkQuesMarkActivity.OnDetailListener {
                        override fun getQuesDetailSuccess(quesMarkDeatilX: QuesMarkDeatil) {
                            quesMarkDeatil = quesMarkDeatilX
                            isAddView = true
                            rootView!!.RlGifLoading.visibility = View.GONE
                            initSubjectAdapter()
                            showQuestionView()
                            setEvalData(parentActivity)
                        }

                        override fun getQuesDetailFaile() {

                        }

                    })

                }, 500)
            }
        }

    }

    private fun setEvalData(parentActivity: AibkQuesMarkActivity) {
        val quesEntity = EvalBody.QuesListEntity(quesMarkDeatil!!)
        quesEntity.stuAnswerList?.addAll(quesMarkDeatil!!.StuAnswerList as MutableList)
        parentActivity.evalBody.quesList.add(quesEntity)
    }

    //初始化小红点
    private fun setShowMark(stuAnswerList: MutableList<StuAnswerMark>) {
        //遍历所有学生，获取到每个学生的相同答题点的答案
        for (i in stuAnswerList.indices) {
            var tempIndex = 0
            for (j in stuAnswerList[i].ChildAnswerList.indices) {
                if (stuAnswerList[i].ChildAnswerList[j].SortIndexType == 0) {
                    if (stuAnswerList[i].ChildAnswerList[j].State == 0 || stuAnswerList[i].ChildAnswerList[j].State == 1) {
                        itemList[tempIndex++].isShowMark = true
                    }
                } else {
                    for (z in stuAnswerList[i].ChildAnswerList[j].ItemList.indices) {
                        if (stuAnswerList[i].ChildAnswerList[j].ItemList[z].State == 0 || stuAnswerList[i].ChildAnswerList[j].ItemList[z].State == 1) {
                            itemList[tempIndex++].isShowMark = true
                        }
                    }
                }
            }
        }
    }

    //查看过后，当前列表的所有学生作答的state设置为2,小红点消失
    //全部评阅完成，小红点消失
    //遍历Parent.evalData 里面保存的State
    // quesMarkDeatil.StuAnswerList 里面的未评阅的State也要修改, 对应的isShowMark 也要修改
    private fun deEvalJob(position: Int) {
        //遍历所有试题
        for (i in activity.evalBody.quesList.indices) {
            //遍历第i个试题所有学生的作答
            for (j in activity.evalBody.quesList[i].stuAnswerList!!.indices) {
                //找到当前界面的quesId
                val stuAnswer = activity.evalBody.quesList[i].stuAnswerList!![j]
                if (stuAnswer.QuesID == quesMarkDeatil?.StuAnswerList?.get(0)!!.QuesID) {
                    //找到对应的答题点State 赋值
                    //sortIndex Type == 0
                    var childIndex = itemList[position].realIndex.toInt()
                    if (stuAnswer.ChildAnswerList[childIndex].SortIndexType == 0) {
                        if (stuAnswer.ChildAnswerList[childIndex].State != 3)
                            stuAnswer.ChildAnswerList[childIndex].State = 2
                        for (t in stuAnswer.ChildAnswerList[childIndex].ItemList.indices) {
                            if (stuAnswer.ChildAnswerList[childIndex].ItemList[t].State != 3)
                                stuAnswer.ChildAnswerList[childIndex].ItemList[t].State = 2
                            activity.mTypeList!![indexA].QuesList[indexB].SortIndexList[t].IsEval = true
                        }
                    } else {
                        for (t in stuAnswer.ChildAnswerList[childIndex].ItemList.indices) {
                            if (stuAnswer.ChildAnswerList[childIndex].ItemList[t].ItemIndex == itemList[position].realChildIndex.toInt() + 1) {
                                if (stuAnswer.ChildAnswerList[childIndex].ItemList[t].State != 3) {
                                    stuAnswer.ChildAnswerList[childIndex].ItemList[t].State = 2
                                    stuAnswer.ChildAnswerList[childIndex].State = 2
                                    activity.mTypeList!![indexA].QuesList[indexB].SortIndexList[t].IsEval = true

                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private fun setStuAnswer(position: Int) {
        //遍历所有学生
        var childIndex = itemList[position].realIndex.toInt()
        for (i in quesMarkDeatil!!.StuAnswerList!!.indices) {
            //遍历第i个学生的答题点,根据sortIndexType 决定给值
            if (quesMarkDeatil!!.StuAnswerList!![i].ChildAnswerList[childIndex].SortIndexType == 0) {
                if (quesMarkDeatil!!.StuAnswerList!![i].ChildAnswerList[childIndex].State != 3)
                    quesMarkDeatil!!.StuAnswerList!![i].ChildAnswerList[childIndex].State = 2
                for (z in quesMarkDeatil!!.StuAnswerList!![i].ChildAnswerList[childIndex].ItemList.indices) {
                    if (quesMarkDeatil!!.StuAnswerList!![i].ChildAnswerList[childIndex].ItemList[z].State != 3) {
                        quesMarkDeatil!!.StuAnswerList!![i].ChildAnswerList[childIndex].ItemList[z].State = 2
                    }
                }
            } else {
                for (z in quesMarkDeatil!!.StuAnswerList!![i].ChildAnswerList[childIndex].ItemList.indices) {
                    if (quesMarkDeatil!!.StuAnswerList!![i].ChildAnswerList[childIndex].ItemList[z].ItemIndex == itemList[position].realChildIndex.toInt() + 1) {
                        if (quesMarkDeatil!!.StuAnswerList!![i].ChildAnswerList[childIndex].ItemList[z].State != 3) {
                            quesMarkDeatil!!.StuAnswerList!![i].ChildAnswerList[childIndex].ItemList[z].State = 2
                            quesMarkDeatil!!.StuAnswerList!![i].ChildAnswerList[childIndex].State = 2
                        }
                    }
                }
            }
        }
    }

    public fun scrollToPosition(position: Int) {
        VpAnswer.setCurrentItem(position, true)
    }

}
